package com.th.coupon.vo;

import com.th.coupon.common.constant.PeriodType;
import com.th.coupon.constant.CouponStatus;
import com.th.coupon.entity.Coupon;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 根据优惠卷状态，用户优惠卷的分类
 * @author 涂航
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CouponClassify {

    /**
     * 可使用的优惠卷
     */
    private List<Coupon> usable;

    /**
     * 已使用的优惠卷
     */
    private List<Coupon> used;

    /**
     * 已过期的优惠卷
     */
    private List<Coupon> expired;

    /**
     * 对当前传入的优惠卷进行分类
     * @param coupons {@link Coupon}
     * @return
     */
    public static CouponClassify classify(List<Coupon> coupons){
        List<Coupon> usables = new ArrayList<>(coupons.size());
        List<Coupon> useds = new ArrayList<>(coupons.size());
        List<Coupon> expireds = new ArrayList<>(coupons.size());

        coupons.forEach(c -> {
            //判断优惠卷是否过期
            boolean isTimeExpire;
            Long curTime = System.currentTimeMillis();
            if(c.getTemplateSDK().getRule().getExpiration().getDeadline()
                    .equals(PeriodType.REGULAR.getCode())){
                isTimeExpire = c.getTemplateSDK().getRule().getExpiration()
                        .getDeadline() <= curTime;
            }else {
                isTimeExpire = DateUtils.addDays(c.getAssignTime()
                        ,c.getTemplateSDK().getRule().getExpiration().getGap()).getTime() <= curTime;
            }

            if(c.getStatus() == CouponStatus.USABLE){
                useds.add(c);
            }if(c.getStatus() == CouponStatus.EXPIRED || isTimeExpire){
                expireds.add(c);
            }else {
                usables.add(c);
            }
        });
        return new CouponClassify(usables,useds,expireds);
    }


}
